import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { defineStore } from 'pinia'
import { carStores } from './carStore'
import { mergeCarAPI } from '@/apis/car'

export const userStores = defineStore(
  'user',
  () => {
    //carStore的实例
    const getCarStore = carStores()

    //数据
    const userInfo = ref({})

    //调用登录API
    const getUserInfo = async ({ account, password }) => {
      const res = await loginAPI({ account, password })

      userInfo.value = res.result

      await mergeCarAPI(
        getCarStore.carList.map((item) => {
          return {
            skuId: item.skuId,
            selected: item.selected,
            count: item.count
          }
        })
      )
      getCarStore.getNewList()
    }

    //退出登录

    const clearUser = () => {
      //清除用户信息
      userInfo.value = {}
      //清除购物车
      getCarStore.clearCar()
    }

    return {
      userInfo,
      getUserInfo,
      clearUser
    }
  },
  {
    persist: true
  }
)
